package com.c.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.alibaba.druid.pool.DruidDataSource;
import com.c.model.example;

import cn.hutool.core.lang.Console;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;

@Repository
public class exampleDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private DruidDataSource ds;

	public List getList() {
		String sql = "SELECT * FROM cloud_t ";
		RowMapper<example> rowMapper = new BeanPropertyRowMapper<example>(example.class);
		return (List) jdbcTemplate.query(sql, rowMapper);
	}

	public List getListUseHuTool() {
		Session session = Session.create(ds);
		List rList = new ArrayList<>();
		try {
			session.beginTransaction();
			Long key = session.insertForGeneratedKey(Entity.create("cloud_t").set("name", "xiaowu"));
			Console.log(key);
			rList = session.query("SELECT * FROM cloud_t order by id desc");
			session.commit();
		} catch (SQLException e) {
			session.quietRollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return rList;
	}

	public void insertByName() {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement ps = connection.prepareStatement("insert into cloud_t(name) values(?)",
						new String[] { "id" });
				ps.setString(1, "chuck1000");
				return ps;
			}

		}, keyHolder);
		// 插入数据 返回主键
		System.out.println(keyHolder.getKey().intValue());
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement ps = connection.prepareStatement("insert into cloud_t(name) values(?)",
						new String[] { "id" });
				ps.setString(1, "chuck6");
				return ps;
			}

		}, keyHolder);

	}
}
